package top.wshape1.shiziapi.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import top.wshape1.shiziapi.message.domain.MessageBroadcast;
import top.wshape1.shiziapi.message.domain.MessageBroadcastRead;
import top.wshape1.shiziapi.common.domain.vo.MessageVo;
import top.wshape1.shiziapi.message.mapper.MessageBroadcastMapper;
import top.wshape1.shiziapi.message.service.MessageBroadcastReadService;
import top.wshape1.shiziapi.message.service.MessageBroadcastService;

import java.util.Date;
import java.util.List;

/**
 * @author Wshape1
 * @description 针对表【t_message_broadcast】的数据库操作Service实现
 * @since 2023-09-18 22:09:06
 */
@Service
public class MessageBroadcastServiceImpl extends ServiceImpl<MessageBroadcastMapper, MessageBroadcast>
        implements MessageBroadcastService {

    @Resource
    private MessageBroadcastReadService broadcastReadService;

    @Override
    public void read(Long msgId, Long userId) {

        MessageBroadcastRead read = broadcastReadService.get(msgId, userId);

        if (read != null) {
            // 未读
            if (read.getIsRead() != 1) {
                broadcastReadService.update(new LambdaUpdateWrapper<MessageBroadcastRead>()
                        .eq(MessageBroadcastRead::getId, read.getId())
                        .set(MessageBroadcastRead::getIsRead, 1)
                        .set(MessageBroadcastRead::getReadTime, new Date())
                );
            }

        } else {

            broadcastReadService.save(new MessageBroadcastRead(null, msgId, userId, 1, new Date()));

        }
    }

    @Override
    public long countUnread(Long userId) {
        // 用总的广播消息数量减去该用户已读消息数量即可
        long all = count();
        long read = broadcastReadService.count(new LambdaQueryWrapper<MessageBroadcastRead>()
                .eq(MessageBroadcastRead::getUserId, userId)
                .eq(MessageBroadcastRead::getIsRead, 1));
        return all - read;
    }

    @Override
    public List<MessageVo> getNotifyMsg(Long userId) {

        List<Long> readMsgIds = broadcastReadService.getMsgIdByUserId(userId);

        List<MessageBroadcast> list = baseMapper.selectNotifyMsg(readMsgIds);

        return list.stream().map(msg -> {
            MessageVo messageVo = new MessageVo();
            BeanUtils.copyProperties(msg, messageVo);
            messageVo.setRead(readMsgIds.contains(msg.getId()));
            messageVo.setBroadcast(true);
            return messageVo;
        }).toList();
    }
}




